{% extends "teacher/base.html" %}

{% block title %}成绩信息管理 - 期末成绩登记统计分析系统{% endblock %}

{% block styles %}
<style>
  .main-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
    margin-left: 250px;
    /* 为侧边栏留出空间 */
    margin-top: 60px;
    /* 为顶部导航栏留出空间 */
    min-height: calc(100vh - 60px);
    /* 减去导航栏高度 */
  }

  .action-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 25px;
    background: white;
    padding: 15px 20px;
    border-radius: var(--border-radius);
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    position: sticky;
    top: 60px;
    /* 导航栏高度 */
    z-index: 100;
  }

  .search-box {
    display: flex;
    gap: 12px;
    flex: 1;
    max-width: 400px;
  }

  .search-box input {
    flex: 1;
    padding: 10px 15px;
    border: 1px solid #e0e0e0;
    border-radius: var(--border-radius);
    font-size: 14px;
    transition: all 0.3s ease;
  }

  .search-box input:focus {
    border-color: var(--primary-blue);
    box-shadow: 0 0 0 2px rgba(9, 132, 227, 0.1);
    outline: none;
  }

  .btn {
    padding: 10px 20px;
    border: none;
    border-radius: var(--border-radius);
    cursor: pointer;
    font-size: 14px;
    font-weight: 500;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    transition: all 0.3s ease;
  }

  .btn i {
    font-size: 16px;
  }

  .btn-primary {
    background: var(--primary-blue);
    color: white;
  }

  .btn-primary:hover {
    background: #0873c4;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(9, 132, 227, 0.2);
  }

  .btn-danger {
    background: #ff6b6b;
    color: white;
  }

  .btn-danger:hover {
    background: #ff5252;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(255, 107, 107, 0.2);
  }

  .btn-success {
    background: #00b894;
    color: white;
  }

  .btn-success:hover {
    background: #00a884;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 184, 148, 0.2);
  }

  .table-container {
    background: white;
    border-radius: var(--border-radius);
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    transition: all 0.3s ease;
  }

  .table-container:hover {
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.15);
  }

  .table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
  }

  .table th,
  .table td {
    padding: 15px 20px;
    text-align: left;
    border-bottom: 1px solid #eee;
  }

  .table th {
    background: #f8f9fa;
    font-weight: 600;
    color: var(--text-primary);
    font-size: 14px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
  }

  .table td {
    color: var(--text-secondary);
    font-size: 14px;
  }

  .table tr:last-child td {
    border-bottom: none;
  }

  .table tr:hover td {
    background: #f8f9fa;
  }

  .table td .btn {
    padding: 6px 12px;
    font-size: 13px;
  }

  .modal {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: 1000;
    backdrop-filter: blur(4px);
  }

  .modal.show {
    display: block;
  }

  .modal-content {
    position: relative;
    background: white;
    margin: 5% auto;
    width: 500px;
    border-radius: 8px;
    box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
    animation: modalSlideIn 0.3s ease;
  }

  @keyframes modalSlideIn {
    from {
      transform: translateY(-20px);
      opacity: 0;
    }

    to {
      transform: translateY(0);
      opacity: 1;
    }
  }

  .modal-header {
    padding: 20px;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .modal-title {
    font-size: 20px;
    color: #333;
    margin: 0;
    font-weight: 600;
  }

  .close {
    font-size: 24px;
    color: #666;
    cursor: pointer;
    transition: all 0.2s ease;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
  }

  .close:hover {
    background: #f8f9fa;
    color: #333;
  }

  .modal-body {
    padding: 20px;
  }

  .form-group {
    margin-bottom: 20px;
  }

  .form-group label {
    display: block;
    margin-bottom: 8px;
    color: #666;
    font-weight: 500;
    font-size: 14px;
  }

  .form-group input[type="file"] {
    width: 100%;
    padding: 10px;
    border: 2px dashed #ddd;
    border-radius: 6px;
    background: #f8f9fa;
    cursor: pointer;
    transition: all 0.3s ease;
  }

  .form-group input[type="file"]:hover {
    border-color: var(--primary-blue);
    background: #f0f7ff;
  }

  .form-group select {
    width: 100%;
    padding: 10px 15px;
    border: 1px solid #ddd;
    border-radius: 6px;
    font-size: 14px;
    color: #333;
    background: white;
    cursor: pointer;
    transition: all 0.3s ease;
  }

  .form-group select:focus {
    border-color: var(--primary-blue);
    box-shadow: 0 0 0 2px rgba(9, 132, 227, 0.1);
    outline: none;
  }

  .alert {
    padding: 15px;
    border-radius: 6px;
    margin-bottom: 0;
  }

  .alert-info {
    background: #e3f2fd;
    border: 1px solid #90caf9;
    color: #1976d2;
  }

  .alert-info h6 {
    color: #1565c0;
    margin-bottom: 10px;
  }

  .alert-info ul {
    padding-left: 20px;
    margin-bottom: 10px;
  }

  .btn-outline-primary {
    color: var(--primary-blue);
    border: 1px solid var(--primary-blue);
    background: transparent;
    padding: 6px 12px;
    border-radius: 4px;
    font-size: 13px;
    transition: all 0.3s ease;
  }

  .btn-outline-primary:hover {
    background: var(--primary-blue);
    color: white;
  }

  .modal-footer {
    padding: 20px;
    border-top: 1px solid #eee;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }

  .modal-backdrop {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: 999;
  }

  .modal-backdrop.fade {
    opacity: 0;
    transition: opacity 0.3s ease;
  }

  .modal-backdrop.show {
    opacity: 1;
  }

  /* 响应式布局调整 */
  @media (max-width: 768px) {
    .main-content {
      margin-left: 0;
      padding: 15px;
    }

    .action-bar {
      position: relative;
      top: 0;
    }

    .search-box {
      max-width: 100%;
    }

    .table-container {
      overflow-x: auto;
    }

    .modal-content {
      width: 90%;
      margin: 10% auto;
    }

    .pagination {
      flex-direction: column;
      gap: 10px;
      padding: 10px;
    }

    .pagination .btn {
      width: 100%;
    }

    .current-page {
      order: -1;
      margin-bottom: 5px;
    }
  }

  /* 添加不及格成绩的样式 */
  .failing-grade {
    color: #ff4757;
    font-weight: bold;
    background-color: rgba(255, 71, 87, 0.1);
    padding: 2px 8px;
    border-radius: 4px;
  }

  .table td {
    padding: 12px 15px;
    vertical-align: middle;
  }

  .text-muted {
    color: #6c757d;
    font-size: 12px;
    margin-top: 4px;
    display: block;
  }

  .alert-warning {
    background: #fff3cd;
    border: 1px solid #ffeeba;
    color: #856404;
  }

  .alert-warning ul {
    padding-left: 20px;
    margin-top: 8px;
  }

  .alert-warning li {
    margin-bottom: 4px;
  }

  .alert-info ol {
    padding-left: 20px;
    margin-top: 8px;
  }

  .alert-info li {
    margin-bottom: 4px;
  }

  /* 批量导入模态框左右padding设置 */
  #importModal .modal-content,
  #importModal .modal-body {
    padding-left: 20px !important;
    padding-right: 20px !important;
  }

  /* 在action-bar中，将"Excel导入"按钮贴在"添加成绩"按钮左侧，间距为10px */
  .action-bar button.btn-primary.me-2 {
    margin-left: 480px;
  }

  /* 分页样式 */
  .pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 15px;
    margin-top: 25px;
    padding: 15px;
    background: white;
    border-radius: var(--border-radius);
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  }

  .pagination .btn {
    padding: 8px 16px;
    min-width: 100px;
    background: white;
    color: var(--primary-blue);
    border: 1px solid var(--primary-blue);
    transition: all 0.3s ease;
  }

  .pagination .btn:hover:not(:disabled) {
    background: var(--primary-blue);
    color: white;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(9, 132, 227, 0.2);
  }

  .pagination .btn:disabled {
    background: #f8f9fa;
    color: #6c757d;
    border-color: #dee2e6;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
  }

  .current-page {
    color: var(--text-primary);
    font-weight: 500;
    font-size: 14px;
    padding: 0 15px;
  }

  #gradeModal .modal-content {
    position: relative;
    background: white;
    margin: 5% auto;
    width: 450px;
    border-radius: var(--border-radius);
    box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
    animation: modalSlideIn 0.3s ease;
  }

  #gradeModal .modal-header {
    padding: 20px;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  #gradeModal .modal-title {
    font-size: 20px;
    color: var(--text-primary);
    margin: 0;
    font-weight: 600;
  }

  #gradeModal .close {
    font-size: 24px;
    color: #666;
    cursor: pointer;
    transition: all 0.2s ease;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
  }

  #gradeModal .close:hover {
    background: #f8f9fa;
    color: var(--text-primary);
  }

  #gradeModal .form-group {
    margin-bottom: 20px;
    padding: 0 20px;
  }

  #gradeModal .form-group label {
    display: block;
    margin-bottom: 8px;
    color: var(--text-secondary);
    font-weight: 500;
    font-size: 14px;
  }

  #gradeModal .form-group input,
  #gradeModal .form-group select {
    width: 100%;
    padding: 10px 15px;
    border: 1px solid #e0e0e0;
    border-radius: var(--border-radius);
    font-size: 14px;
    transition: all 0.3s ease;
  }

  #gradeModal .form-group input:focus,
  #gradeModal .form-group select:focus {
    border-color: var(--primary-blue);
    box-shadow: 0 0 0 2px rgba(9, 132, 227, 0.1);
    outline: none;
  }

  #gradeModal .modal-footer {
    padding: 20px;
    border-top: 1px solid #eee;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }

  @media (max-width: 768px) {
    #gradeModal .modal-content {
      width: 90%;
      margin: 10% auto;
    }
  }
</style>
{% endblock %}

{% block content %}
<div class="action-bar">
  <div class="search-box">
    <input type="text" id="searchInput" placeholder="搜索学生/课程名...">
    <button class="btn btn-primary" onclick="searchGrades()">搜索</button>
  </div>
  <button class="btn btn-primary me-2" onclick="showImportModal()">
    <i class="fas fa-file-excel"></i> Excel导入
  </button>
  <button class="btn btn-primary" onclick="showAddModal()">添加成绩</button>
</div>

<div class="table-container">
  <table class="table">
    <thead>
      <tr>
        <th>学号</th>
        <th>姓名</th>
        <th>课程</th>
        <th>学期</th>
        <th>平时成绩</th>
        <th>期末成绩</th>
        <th>总评成绩</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody id="gradeTableBody">
      {% for grade in grades %}
      <tr>
        <td>{{ grade.student_number }}</td>
        <td>{{ grade.student_name }}</td>
        <td>{{ grade.course_name }}</td>
        <td>{{ grade.semester }}</td>
        <td class="{% if grade.regular_score < 60 %}failing-grade{% endif %}">{{ "%.1f"|format(grade.regular_score) }}
        </td>
        <td class="{% if grade.final_score < 60 %}failing-grade{% endif %}">{{ "%.1f"|format(grade.final_score) }}</td>
        <td class="{% if grade.total_score < 60 %}failing-grade{% endif %}">{{ "%.1f"|format(grade.total_score) }}</td>
        <td>
          <button class="btn btn-primary" onclick="showEditModal('{{ grade.grade_id }}')">编辑</button>
          <button class="btn btn-danger" onclick="deleteGrade('{{ grade.grade_id }}')">删除</button>
        </td>
      </tr>
      {% endfor %}
    </tbody>
  </table>

  <!-- 分页控件 -->
  {% if pagination.total > 20 %}
  <div class="pagination">
    {% if pagination.has_prev %}
    <a href="{{ url_for('teacher_grade.grades', page=pagination.prev_num) }}" class="btn">上一页</a>
    {% else %}
    <button class="btn" disabled>上一页</button>
    {% endif %}

    <span class="current-page">第 {{ pagination.page }} 页，共 {{ pagination.pages }} 页</span>

    {% if pagination.has_next %}
    <a href="{{ url_for('teacher_grade.grades', page=pagination.next_num) }}" class="btn">下一页</a>
    {% else %}
    <button class="btn" disabled>下一页</button>
    {% endif %}
  </div>
  {% endif %}
</div>

<!-- 添加/编辑成绩模态框 -->
<div id="gradeModal" class="modal">
  <div class="modal-content">
    <div class="modal-header">
      <h3 class="modal-title" id="modalTitle">添加成绩</h3>
      <span class="close" onclick="closeModal('gradeModal')">&times;</span>
    </div>
    <form id="gradeForm">
      <input type="hidden" id="gradeId">
      <div class="form-group">
        <label for="studentId">学生</label>
        <select id="studentId" required>
          {# 按学号倒序显示学生 #}
          {% for student in students|sort(attribute='student_number', reverse=True) %}
          <option value="{{ student.student_number }}">{{ student.name }} ({{ student.student_number }})</option>
          {% endfor %}
        </select>
      </div>
      <div class="form-group">
        <label for="courseId">课程</label>
        <select id="courseId" required>
          {% for course in courses %}
          <option value="{{ course.course_id }}">{{ course.course_name }}</option>
          {% endfor %}
        </select>
      </div>
      <div class="form-group">
        <label for="semester">学期</label>
        <select id="semester" required>
          {% for semester in semesters %}
          <option value="{{ semester }}">{{ semester }}</option>
          {% endfor %}
        </select>
      </div>
      <div class="form-group">
        <label for="regularScore">平时成绩</label>
        <input type="number" id="regularScore" step="0.1" required
          oninput="updateTotalScore(); validateScore(this, 'regularScoreError')">
        <div id="regularScoreError" style="color: red; font-size: 13px; display: none;">请输入0-100之间的分数</div>
      </div>
      <div class="form-group">
        <label for="finalScore">期末成绩</label>
        <input type="number" id="finalScore" step="0.1" required
          oninput="updateTotalScore(); validateScore(this, 'finalScoreError')">
        <div id="finalScoreError" style="color: red; font-size: 13px; display: none;">请输入0-100之间的分数</div>
      </div>
      <!-- 总评成绩预览 -->
      <div class="form-group">
        <label>总评成绩预览</label>
        <input type="text" id="totalScorePreview" readonly style="background:#f8f9fa; color:#333;">
        <div id="totalScoreError" style="color: red; font-size: 13px; display: none;">总评成绩应在0-100之间</div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" onclick="closeModal('gradeModal')">取消</button>
        <button type="submit" class="btn btn-success" onclick="closeModal('gradeModal')">保存</button>
      </div>
    </form>
  </div>
</div>

<!-- Excel导入模态框 -->
<div id="importModal" class="modal">
  <div class="modal-content">
    <div class="modal-header">
      <h3 class="modal-title">Excel批量导入成绩</h3>
      <span class="close" onclick="closeModal('importModal')">&times;</span>
    </div>
    <form id="importForm" enctype="multipart/form-data">
      <div class="form-group">
        <label for="excelFile">选择Excel文件</label>
        <input type="file" id="excelFile" name="file" accept=".xlsx,.xls" required>
        <small class="text-muted">支持.xlsx和.xls格式的Excel文件</small>
      </div>
      <div class="form-group">
        <label for="importClass">选择班级</label>
        <select id="importClass" name="class_id" required>
          <option value="">请选择班级</option>
          {% for class in classes %}
          <option value="{{ class.class_id }}">{{ class.class_name }}</option>
          {% endfor %}
        </select>
      </div>
      <div class="form-group">
        <label for="importCourse">选择课程</label>
        <select id="importCourse" name="course_id" required>
          <option value="">请选择课程</option>
          {% for course in courses %}
          <option value="{{ course.course_id }}">{{ course.course_name }}</option>
          {% endfor %}
        </select>
      </div>
      <div class="form-group">
        <label for="importSemester">选择学期</label>
        <select id="importSemester" name="semester" required>
          <option value="">请选择学期</option>
          {% for semester in semesters %}
          <option value="{{ semester }}">{{ semester }}</option>
          {% endfor %}
        </select>
      </div>
      <div class="form-group">
        <div class="alert alert-info">
          <h6><i class="fas fa-info-circle"></i> Excel文件格式说明：</h6>
          <div class="alert alert-warning mb-2">
            <ul class="mb-0">
              <li>请勿修改表头名称</li>
              <li>成绩必须是0-100之间的数字</li>
              <li>学号必须与系统中的学生信息匹配</li>
              <li>请勿添加其他列或修改列的顺序</li>
            </ul>
          </div>
          <a href="/static/templates/grade_template.xlsx" class="btn btn-sm btn-outline-primary mt-2"
            download="成绩导入模板.xlsx">
            <i class="fas fa-download"></i> 下载模板文件
          </a>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" onclick="closeModal('importModal')">取消</button>
        <button type="button" class="btn btn-primary" onclick="importGrades()">导入</button>
      </div>
    </form>
  </div>
</div>

<!-- 导入结果提示模态框 -->
<div id="importResultModal" class="modal">
  <div class="modal-content">
    <div class="modal-header">
      <h3 class="modal-title">导入结果</h3>
      <span class="close" onclick="closeModal('importResultModal')">&times;</span>
    </div>
    <div class="modal-body">
      <div id="importResult"></div>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-primary" onclick="closeModal('importResultModal')">确定</button>
    </div>
  </div>
</div>

<script>
  // 获取 CSRF 令牌
  function getCsrfToken() {
    return document.querySelector('meta[name="csrf-token"]').getAttribute('content');
  }

  // 显示添加模态框
  function showAddModal() {
    document.getElementById('modalTitle').textContent = '添加成绩';
    document.getElementById('gradeId').value = '';
    document.getElementById('gradeForm').reset();
    document.getElementById('gradeModal').style.display = 'block';
  }

  // 显示编辑模态框
  function showEditModal(gradeId) {
    document.getElementById('modalTitle').textContent = '编辑成绩';
    document.getElementById('gradeId').value = gradeId;

    // 获取成绩信息
    fetch(`/teacher/api/grades/${gradeId}`, {
      headers: {
        'X-CSRFToken': getCsrfToken()
      }
    })
      .then(response => response.json())
      .then(data => {
        document.getElementById('studentId').value = data.student_number;
        document.getElementById('courseId').value = data.course_id;
        document.getElementById('semester').value = data.semester;
        document.getElementById('regularScore').value = data.regular_score;
        document.getElementById('finalScore').value = data.final_score;
        document.getElementById('gradeModal').style.display = 'block';
      })
      .catch(error => {
        console.error('Error:', error);
        alert('获取成绩信息失败');
      });
  }

  // 关闭模态框
  function closeModal(modalId) {
    const modal = document.getElementById(modalId);
    modal.style.display = 'none';
    const backdrop = document.querySelector('.modal-backdrop');
    if (backdrop) {
      backdrop.remove();
    }
  }

  // 删除成绩
  function deleteGrade(gradeId) {
    if (confirm('确定要删除这条成绩记录吗？')) {
      fetch(`/teacher/api/grades/${gradeId}`, {
        method: 'DELETE',
        headers: {
          'X-CSRFToken': getCsrfToken()
        }
      })
        .then(response => response.json())
        .then(data => {
          if (data.success) {
            location.reload();
          } else {
            alert(data.message || '删除失败');
          }
        })
        .catch(error => {
          console.error('Error:', error);
          alert('删除失败');
        });
    }
  }

  // 搜索成绩
  function searchGrades() {
    const searchText = document.getElementById('searchInput').value.trim();
    const page = 1; // 重置到第一页

    // 显示加载状态
    const tbody = document.getElementById('gradeTableBody');
    tbody.innerHTML = '<tr><td colspan="8" style="text-align: center;">正在搜索...</td></tr>';

    // 构建URL，包含搜索参数和分页参数
    const url = `/teacher/api/grades?search=${encodeURIComponent(searchText)}&page=${page}`;

    fetch(url, {
      headers: {
        'X-CSRFToken': getCsrfToken()
      }
    })
      .then(response => {
        if (!response.ok) {
          throw new Error('搜索请求失败');
        }
        return response.json();
      })
      .then(data => {
        tbody.innerHTML = '';

        if (data.success && data.grades && data.grades.length > 0) {
          data.grades.forEach(grade => {
            const row = document.createElement('tr');
            row.setAttribute('data-grade-id', grade.grade_id);
            row.innerHTML = `
              <td>${grade.student_number || ''}</td>
              <td>${grade.student_name || ''}</td>
              <td>${grade.course_name || ''}</td>
              <td>${grade.semester || ''}</td>
              <td class="${grade.regular_score < 60 ? 'failing-grade' : ''}">${grade.regular_score ? grade.regular_score.toFixed(1) : ''}</td>
              <td class="${grade.final_score < 60 ? 'failing-grade' : ''}">${grade.final_score ? grade.final_score.toFixed(1) : ''}</td>
              <td class="${grade.total_score < 60 ? 'failing-grade' : ''}">${grade.total_score ? grade.total_score.toFixed(1) : ''}</td>
            <td>
              <button class="btn btn-primary" onclick="showEditModal('${grade.grade_id}')">编辑</button>
              <button class="btn btn-danger" onclick="deleteGrade('${grade.grade_id}')">删除</button>
            </td>
          `;
            tbody.appendChild(row);
          });
        } else {
          tbody.innerHTML = '<tr><td colspan="8" style="text-align: center;">没有找到匹配的成绩记录</td></tr>';
        }

        // 更新分页控件
        if (data.pagination) {
          updatePagination(data.pagination);
        }
      })
      .catch(error => {
        console.error('Error:', error);
        tbody.innerHTML = '<tr><td colspan="8" style="text-align: center; color: red;">搜索失败</td></tr>';
      });
  }

  // 更新分页控件
  function updatePagination(pagination) {
    const paginationDiv = document.querySelector('.pagination');
    if (!paginationDiv) return;

    // 只有当总记录数大于20时才显示分页
    if (pagination.total <= 20) {
      paginationDiv.style.display = 'none';
      return;
    }

    paginationDiv.style.display = 'flex';
    paginationDiv.innerHTML = '';

    // 获取当前搜索文本
    const searchText = document.getElementById('searchInput').value.trim();
    const searchParam = searchText ? `&search=${encodeURIComponent(searchText)}` : '';

    const prevButton = document.createElement(pagination.has_prev ? 'a' : 'button');
    prevButton.className = 'btn';
    prevButton.textContent = '上一页';
    if (pagination.has_prev) {
      prevButton.href = `/teacher/grades?page=${pagination.current_page - 1}${searchParam}`;
    } else {
      prevButton.disabled = true;
    }
    paginationDiv.appendChild(prevButton);

    const pageInfo = document.createElement('span');
    pageInfo.className = 'current-page';
    pageInfo.textContent = `第 ${pagination.current_page} 页，共 ${pagination.pages} 页`;
    paginationDiv.appendChild(pageInfo);

    const nextButton = document.createElement(pagination.has_next ? 'a' : 'button');
    nextButton.className = 'btn';
    nextButton.textContent = '下一页';
    if (pagination.has_next) {
      nextButton.href = `/teacher/grades?page=${pagination.current_page + 1}${searchParam}`;
    } else {
      nextButton.disabled = true;
    }
    paginationDiv.appendChild(nextButton);
  }

  // 添加搜索框回车事件
  document.getElementById('searchInput').addEventListener('keypress', function (e) {
    if (e.key === 'Enter') {
      searchGrades();
    }
  });

  // 实时校验成绩输入，超出范围时显示提示
  function validateScore(input, errorId) {
    const value = parseFloat(input.value);
    const errorDiv = document.getElementById(errorId);
    if (isNaN(value) || value < 0 || value > 100) {
      errorDiv.style.display = 'block';
    } else {
      errorDiv.style.display = 'none';
    }
  }

  // 实时计算总评成绩并预览
  function updateTotalScore() {
    const regular = parseFloat(document.getElementById('regularScore').value);
    const final = parseFloat(document.getElementById('finalScore').value);
    let total = '';
    if (!isNaN(regular) && !isNaN(final)) {
      // 如有权重请修改此处，默认50%+50%
      total = (regular * 0.5 + final * 0.5).toFixed(1);
    }
    document.getElementById('totalScorePreview').value = total;
    // 校验总评范围
    const errorDiv = document.getElementById('totalScoreError');
    if (total !== '' && (total < 0 || total > 100)) {
      errorDiv.style.display = 'block';
    } else {
      errorDiv.style.display = 'none';
    }
  }

  // 提交表单
  document.getElementById('gradeForm').onsubmit = function (e) {
    e.preventDefault();
    const gradeId = document.getElementById('gradeId').value;
    // 验证输入
    const studentNumber = document.getElementById('studentId').value;
    const courseId = document.getElementById('courseId').value;
    const semester = document.getElementById('semester').value;
    const regularScore = document.getElementById('regularScore').value;
    const finalScore = document.getElementById('finalScore').value;
    const totalScore = document.getElementById('totalScorePreview').value;
    if (!studentNumber || !courseId || !semester || !regularScore || !finalScore) {
      alert('请填写所有必填字段');
      return;
    }
    // 先判断是否有负数成绩
    if (regularScore < 0 || finalScore < 0 || totalScore < 0) {
      alert('成绩不能为负');
      return;
    }
    // 再判断是否超出100
    if (regularScore > 100 || finalScore > 100 || totalScore > 100) {
      alert('所有成绩必须在0-100之间');
      return;
    }
    const data = {
      student_number: studentNumber,
      course_id: parseInt(courseId),
      semester: semester,
      regular_score: parseFloat(regularScore),
      final_score: parseFloat(finalScore)
    };

    const url = gradeId ? `/teacher/api/grades/${gradeId}` : '/teacher/api/grades';
    const method = gradeId ? 'PUT' : 'POST';

    // 禁用提交按钮，防止重复提交
    const submitButton = this.querySelector('button[type="submit"]');
    submitButton.disabled = true;
    submitButton.textContent = '保存中...';

    fetch(url, {
      method: method,
      headers: {
        'Content-Type': 'application/json',
        'X-CSRFToken': getCsrfToken()
      },
      body: JSON.stringify(data)
    })
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          alert('保存成功');
          // 关闭模态框
          closeModal('gradeModal');
          // 重新加载页面
          window.location.reload();
        } else {
          throw new Error(data.message || '保存失败');
        }
      })
      .catch(error => {
        console.error('Error:', error);
        alert(error.message || '保存失败，请稍后重试');
      })
      .finally(() => {
        // 恢复提交按钮状态
        submitButton.disabled = false;
        submitButton.textContent = '保存';
      });
  };

  // 显示导入模态框
  function showImportModal() {
    // 重置表单
    document.getElementById('importForm').reset();
    // 显示模态框
    const modal = document.getElementById('importModal');
    modal.style.display = 'block';
    modal.classList.add('show');
    document.body.classList.add('modal-open');
    const backdrop = document.createElement('div');
    backdrop.className = 'modal-backdrop fade show';
    document.body.appendChild(backdrop);
  }

  // 导入成绩
  function importGrades() {
    const formData = new FormData(document.getElementById('importForm'));
    const file = document.getElementById('excelFile').files[0];

    if (!file) {
      showError('请选择Excel文件');
      return;
    }

    if (!formData.get('class_id') || !formData.get('course_id') || !formData.get('semester')) {
      showError('请选择班级、课程和学期');
      return;
    }

    formData.append('file', file);

    // 禁用导入按钮，防止重复提交
    const importButton = document.querySelector('#importModal .btn-primary');
    importButton.disabled = true;
    importButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 导入中...';

    fetch('/teacher/api/grades/import', {
      method: 'POST',
      headers: {
        'X-CSRFToken': getCsrfToken()
      },
      body: formData
    })
      .then(response => response.json())
      .then(result => {
        if (result.success) {
          // 批量导入成功时先弹出alert
          alert('批量导入成功');
          showImportResult(result);
          // 关闭导入模态框
          closeModal('importModal');
          // 重新加载页面
          setTimeout(() => {
            window.location.reload();
          }, 3000);
        } else {
          showError(result.message || '导入失败');
        }
      })
      .catch(error => {
        console.error('Error:', error);
        showError('导入失败，请稍后重试');
      })
      .finally(() => {
        // 恢复导入按钮状态
        importButton.disabled = false;
        importButton.innerHTML = '导入';
      });
  }

  // 显示导入结果
  function showImportResult(result) {
    // 如果导入成功，强制显示"批量导入成功"
    const message = result.success ? '批量导入成功' : (result.message || '导入失败');
    const resultHtml = `
      <div class="alert ${result.success ? 'alert-success' : 'alert-warning'}">
        <h6><i class="fas ${result.success ? 'fa-check-circle' : 'fa-exclamation-triangle'}"></i> ${message}</h6>
        ${result.details ? `
          <div class="mt-3">
            <h6>详细信息：</h6>
            <ul class="mb-0">
              ${result.details.map(detail => `<li>${detail}</li>`).join('')}
            </ul>
          </div>
        ` : ''}
      </div>
    `;

    document.getElementById('importResult').innerHTML = resultHtml;
    const modal = document.getElementById('importResultModal');
    modal.style.display = 'block';
    modal.classList.add('show');
    document.body.classList.add('modal-open');
    const backdrop = document.createElement('div');
    backdrop.className = 'modal-backdrop fade show';
    document.body.appendChild(backdrop);

    // 自动关闭：3秒后关闭提示框
    if (result.success) {
      setTimeout(() => {
        closeModal('importResultModal');
      }, 3000);
    }
  }

  // 显示错误信息
  function showError(message) {
    const resultHtml = `
      <div class="alert alert-danger">
        <i class="fas fa-exclamation-circle"></i> ${message}
      </div>
    `;

    document.getElementById('importResult').innerHTML = resultHtml;
    const modal = document.getElementById('importResultModal');
    modal.style.display = 'block';
    modal.classList.add('show');
    document.body.classList.add('modal-open');
    const backdrop = document.createElement('div');
    backdrop.className = 'modal-backdrop fade show';
    document.body.appendChild(backdrop);
  }

  // 为所有模态框的关闭按钮添加事件监听
  document.addEventListener('DOMContentLoaded', function () {
    // 为所有模态框的关闭按钮添加点击事件
    document.querySelectorAll('.modal .btn-close, .modal .btn-secondary').forEach(button => {
      button.addEventListener('click', function () {
        const modal = this.closest('.modal');
        closeModal(modal.id);
      });
    });

    // 点击模态框背景时关闭
    document.querySelectorAll('.modal').forEach(modal => {
      modal.addEventListener('click', function (e) {
        if (e.target === this) {
          closeModal(this.id);
        }
      });
    });
  });
</script>
{% endblock %}

{% block scripts %}
{{ super() }}
<script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
<script>
  // ... existing code ...
</script>
{% endblock %}